package ltd.followkba.comment;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.SecureRandom;

import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;

import ltd.followkba.comment.utils.CodeBase64;


import static ltd.advskin.MSKIN.MSTRING;
import static ltd.followkba.comment.MKCC.APPC_GET_RANK_LIST;
import static ltd.followkba.comment.MKCC.APPC_USER_LOGIN;
import static ltd.followkba.comment.MKCC.cKCB_SW_VV_MUSIC;

/**
 * Created by Administrator on 2016/11/22.
 */

public class KgVvMusic extends KgAppBase {
    private static String mCid = "32a9c43d85345ab6bd0602668d5f894c";
    private static String mKey = "b100ee19f66a443484acb9636dd96be8";

    public KgVvMusic(){
        SwitchAppType(cKCB_SW_VV_MUSIC);
    }

    public void Write(){


        String action = "action=38&parameter={\"platform\":\"Android\",\"pushTokenID\":\"com.vv51.mvbox%3Aeae4b2a29b7ede6130b05999e280fae8d72ec586\",\"pw\":\"123456\",\"UserIdS\":\"17854171622\"}";
        String key = "b100ee19f66a443484acb9636dd96be8";
        String enc = encRequest(action,key);
        String ret = http_get_request("/sod?"+enc,key);
        MSTRING("aaaaa " + ret );
        //MLOG("aaaaa");
    }


    public ResultNet WriteCommand(int type, String aux1, String aux2){
        String gsLocal_1;
        String gsLocal_2;
        String gsLocal_3;
        int g4Local_1;
        ResultNet resultNet = new ResultNet();
        switch (type) {
            case APPC_USER_LOGIN:
      //          gsLocal_1 = "action=38&parameter={\"platform\":\"Android\",\"pushTokenID\":\"com.vv51.mvbox%3Aeae4b2a29b7ede6130b05999e280fae8d72ec586\",\"pw\":\"123456\",\"UserIdS\":\"17854171622\"}";
                gsLocal_1 = "action=38&parameter={\"platform\":\"Android\",\"pushTokenID\":\"com.vv51.mvbox%3Ab4865923d22e2c6efb407111f8a291d93cdcb19d\",\"pw\":\"aa1234567\",\"UserIdS\":\"13713698152\"}";
                MSTRING("APPC_USER_LOGIN " + gsLocal_1);
                gsLocal_2 = encRequest(gsLocal_1,mKey);
                http_get_request("/sod?"+gsLocal_2,mKey);
                break;
            case APPC_GET_RANK_LIST:
                gsLocal_1 = "action=36003&parameter={\"beginIndex\":0,\"discoverId\":\"2\",\"rows\":30}";
           //     gsLocal_1 = "action=62&parameter={\"evt\":0,\"mobileType\":\"android\",\"prf\":0}";
                gsLocal_2 = encRequest(gsLocal_1,mKey);
                http_get_request("/sod?"+gsLocal_2,mKey);
                break;
        }


        return resultNet;
    }

    //解密请求
    private String dencRequest(String quest, String key){
        byte[] bs = new byte[0];
        try {
            bs = CodeBase64.decode(quest.getBytes());
            byte[] con = dencReturnByte(bs,key.getBytes());
            System.out.println(byte2Hex(con));
            byte[] re = new byte[(con[3]) & 0xFF];
            System.arraycopy(con,4,re,0,re.length);
            return new String(con);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "";
    }
    //解密返回
    private String dencReturn(byte[] re , String key){
        return  new String(dencReturnByte(re,key.getBytes()));
    }
    //加密请求
    private String encRequest(String request , String key){
        byte[] content = new byte[request.length()+4];
        content[3] = (byte) request.length();
        System.arraycopy(request.getBytes(),0,content,4,request.length());
        byte[] key_b = key.getBytes();
        System.out.println("key len:"+key_b.length);
        //System.out.println(byte2Hex(key));
        byte[] result = RC4.encrypt(content,key_b);
        System.out.println("result len:"+result.length);
//        return  new String(java.util.CodeBase64.getEncoder().encode(result));
        return  new String(CodeBase64.encodeBytes(result));
    }
    public String getNewKey(){
        String path = "https://m0.mvbox.cn/p.1";
        MSTRING("getNewKey 1 ");
        try {
            sslContext();
            MSTRING("getNewKey 2 ");
            HttpsURLConnection connection = (HttpsURLConnection) new URL(path).openConnection();
            connection.setRequestMethod("GET");
            connection.setRequestProperty("X-CID", mCid);
            connection.setRequestProperty("X-SEC", "P");
            connection.setRequestProperty("Connection", "Keep-Alive");
            connection.setUseCaches(false);
            MSTRING("getNewKey 3");
            connection.connect();
            MSTRING("getNewKey 5");
            InputStream inputStream = connection.getInputStream();
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            byte[] tmp = new byte[10];
            MSTRING("getNewKey 7");
            while (true){
                int len = inputStream.read(tmp,0,10);
                if (len == -1)
                    break;
                byteArrayOutputStream.write(tmp,0,len);
            }
            inputStream.close();
            byte[] result = byteArrayOutputStream.toByteArray();
            byteArrayOutputStream.close();
            MSTRING("getNewKey 3");
//            System.out.println(byte2Hex(result));
//            System.out.println(new String(result));
//            System.out.println(dencReturn(result,"sup.m.51vv.com"));
            String gsLocal_1 = dencReturn(result,"sup.m.51vv.com");
            MSTRING("sup.m.51vv.com  "+gsLocal_1);
            if (gsLocal_1.length() > 36) {
                gsLocal_1 = gsLocal_1.substring(4, 4+32);
            }
            return gsLocal_1;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }
    private String http_get_request(String param, String key){
        try {
            URL url = new URL("http://m0.mvbox.cn"+param);
            System.out.println(url.toString());
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");
            connection.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
            connection.setRequestProperty("Gps-Location","[0,0]");
            connection.setRequestProperty("X-PRODUCT","vv_android,2.0.4.41");
            connection.setRequestProperty("X-CID",mCid);
            connection.setRequestProperty("X-SEC","P,C");
            connection.setRequestProperty("X-CHANNEL","1000");
            connection.setRequestProperty("User-Agent","VVMusic 2.0.4 rv:41 (Xiaomi Redmi 3; Android 5.1.1; zh_CN)");
            connection.connect();
            InputStream inputStream = connection.getInputStream();
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            byte[] tmp = new byte[10];
            while (true){
                int len = inputStream.read(tmp,0,10);
                if (len == -1)
                    break;
                byteArrayOutputStream.write(tmp,0,len);
            }
            inputStream.close();
            MSTRING("http_get_request 3");
            byte[] result = byteArrayOutputStream.toByteArray();
            System.out.println("返回长度："+result.length);
            System.out.println(byte2Hex(result));
            System.out.println("解密返回：");
            byte[] den = dencReturnByte(result,key.getBytes());
            System.out.println(new String(den,"utf-8"));
            System.out.println(byte2Hex(den));
            return new String(den,"utf-8");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }
    private void sslContext(){
        try {
            Manager manager = new Manager();
            Verifier verifier = new Verifier();
            SSLContext context = SSLContext.getInstance("TLS");
            TrustManager[]ms = new TrustManager[]{manager};
            context.init(null,ms,new SecureRandom());
            HttpsURLConnection.setDefaultSSLSocketFactory(context.getSocketFactory());
            HttpsURLConnection.setDefaultHostnameVerifier(verifier);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    private byte[] dencReturnByte(byte[] re,byte[] key){
        return RC4.decrypt(re,key);
    }

    private String byte2Hex(byte [] bs){
        StringBuilder builder = new StringBuilder();
        int i = 0;
        for (byte b : bs) {
            String hex = Integer.toHexString(b & 0xFF);
            if (hex.length() == 1) {
                builder.append("0");
            }
            builder.append(hex);
            builder.append(" ");
            ++i;
            if(i%64 == 0)
                builder.append("\n");
        }
        return  builder.toString();
    }

}
